﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization ;
using System.IO;
using System.ServiceModel;

using VelesDBBL ;

namespace VelesServiceLibrary
{
    public class ServiceManager
    {
        ServiceOption serviceOption;

        public ServiceManager(string path)
        {
            serviceOption = new ServiceOption();
            string optionFileName = path + "//" + ServiceOption.FileName;
            try { LoadOption(optionFileName); }
            catch { SaveOption(optionFileName); }

            StartDBCore();
            StartService();            
        }

        private void StartDBCore()
        {
            DBManager.Server = serviceOption.Server;
            DBManager.DbName = serviceOption.DbName;
            DBManager.SaPassword = serviceOption.SaPassword;
        }


        void StartService()
        {
            Type serviceType = typeof(VelesServiceLibrary.VelesService);
            Uri serviceUri = new Uri(serviceOption.ServiceURI);
            ServiceHost host = new ServiceHost(serviceType, serviceUri);

            host.AddServiceEndpoint(typeof(VelesServiceLibrary.IVelesService), new BasicHttpBinding(), "");
            host.Open();
        
        }

        private void SaveOption(string optionFileName)
        {
            XmlSerializer myXmlSer = new XmlSerializer(typeof(ServiceOption));
            StreamWriter myWriter = new StreamWriter(optionFileName,true  );
            myXmlSer.Serialize(myWriter, serviceOption);
            myWriter.Close();
        }

        private void LoadOption(string optionFileName)
        {
            FileStream mySet=null ;
            XmlSerializer myXmlSer = new XmlSerializer(typeof(ServiceOption));
            try
            {
                mySet = new FileStream(optionFileName, FileMode.Open);
                serviceOption = (ServiceOption)myXmlSer.Deserialize(mySet);
            }
            catch { throw new Exception(); }
            finally { mySet.Close(); }
        }
    }
}
